package com.tyq.auth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyq.auth.common.ResultData;
import com.tyq.auth.common.ReturnCode;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义请求未认证处理器
 * 访问接口时未登录，则进入此处理器处理
 *
 * @author 谭永强
 * @date 2024-05-21
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ResultData<Authentication> resultData = new ResultData<>();
        resultData.setCode(ReturnCode.UN_AUTHENTICATED.getCode());
        resultData.setMessage("访问此资源需要完全身份认证!");
        objectMapper.writeValue(response.getWriter(), resultData);
        //response.sendRedirect("/login.html");
    }
}
